import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layouts/Layout.vue'
import Login from '@/pages/Login.vue'
import NotFound from '@/pages/NotFound.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/pages/Dashboard.vue'),
        meta: { requiresAuth: true, title: 'menu.dashboard', icon: 'Odometer' }
      },
      {
        path: 'user',
        name: 'UserManagement',
        component: () => import('@/pages/UserManagement.vue'),
        meta: { requiresAuth: true, title: 'menu.userManagement', icon: 'User' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 从Pinia持久化存储中获取token
  const userStore = localStorage.getItem('user-store')
  const token = userStore ? JSON.parse(userStore).token : null
  
  if (to.meta.requiresAuth && !token) {
    next({ name: 'Login' })
  } else if (to.path === '/login' && token) {
    next({ path: '/' })
  } else {
    next()
  }
})

export default router